<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="ByteBuf 详解, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>ByteBuf 详解 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/2.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">ByteBuf 详解</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/ByteBuf-%E8%AF%A6%E8%A7%A3/">
                                <span class="chip bg-color">ByteBuf 详解</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Netty/" class="post-category">
                                Netty
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-01-02
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    16 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>正如我们先前所指出的，**网络数据的基本单位永远是 byte(字节)**。Java NIO 提供 <code>ByteBuffer</code> 作为字节的容器，但这个类是过于复杂，有点难以使用。</p>
<p>Netty 中 <code>ByteBuffer </code> 的替代是 <code>ByteBuf</code>，一个强大的实现，解决 JDK 的 API 的限制，以及为网络应用程序开发者一个更好的工具。 但 <code>ByteBuf </code>并不仅仅暴露操作一个字节序列的方法; 这也是专门的 Netty 的 <code>ChannelPipeline </code> 的语义设计。</p>
<p>在本章中，我们会说明相比于 JDK 的 API，<code>ByteBuf</code> 所提供的卓越的功能和灵活性。这也将使我们能够更好地理解了 Netty 的数据处理。</p>
<h2 id="1-Buffer-API"><a href="#1-Buffer-API" class="headerlink" title="1. Buffer API"></a>1. Buffer API</h2><p>主要包括</p>
<ul>
<li><code>ByteBuf</code></li>
<li><code>ByteBufHolder</code></li>
</ul>
<p>Netty 使用 <strong>reference-counting (引用计数)</strong> 来判断何时可以释放 <code>ByteBuf </code>或 <code>ByteBufHolder </code>和其他相关资源，从而可以利用池和其他技巧来提高性能和降低内存的消耗。这一点上不需要开发人员做任何事情，但是<strong>在开发 Netty 应用程序时，尤其是使用 <code>ByteBuf </code>和 <code>ByteBufHolder </code>时，你应该尽可能早地释放池资源</strong>。 </p>
<blockquote>
<p>💡 <strong>引用计数</strong>：学习过 JVM 的小伙伴应该知道垃圾回收有<u>引用计数法</u>和<u>可达性分析</u>这两种算法判断对象是否存活，Netty 就使用了 引用计数法来优化内存的使用。引用计数确保了当对象的引用计数大于 1 时，对象就不会被释放，当计数减少至 0 时， 对象就会被释放，如果程序访问一个已被释放的引用计数对象，那么将会导致一个  <code>IllegalReferenceCountException</code> 异常。 在 Netty 中，<code>ByteBuf</code> 和 <code>ByteBufHolder</code> 都实现了 <code>ReferenceCounted</code> 接口。</p>
</blockquote>
<p>Netty 的 <code>Buffer</code> API 提供了几个优势：</p>
<ul>
<li>可以自定义缓冲类型</li>
<li>通过一个内置的复合缓冲类型实现零拷贝</li>
<li>扩展性好，比如 <code>StringBuilder</code></li>
<li>不需要调用 <code>flip()</code> 来切换读/写模式</li>
<li>读取和写入索引分开</li>
<li>方法链</li>
<li>引用计数</li>
<li>Pooling (池)</li>
</ul>
<h2 id="2-ByteBuf-—-Netty-字节数据的容器"><a href="#2-ByteBuf-—-Netty-字节数据的容器" class="headerlink" title="2. ByteBuf — Netty 字节数据的容器"></a>2. ByteBuf — Netty 字节数据的容器</h2><p><code>ByteBuf</code> 是一个很好的经过优化的数据容器，我们可以将字节数据有效的添加到 <code>ByteBuf</code> 中或从 <code>ByteBuf</code> 中获取数据。<code>ByteBuf</code> 有 2 部分：一个用于读，一个用于写。我们可以按顺序的读取数据，也可以通过调整读取数据的索引或者直接将读取位置索引作为参数传递给 get 方法来重复读取数据。</p>
<h3 id="①-ByteBuf-如何在工作"><a href="#①-ByteBuf-如何在工作" class="headerlink" title="① ByteBuf 如何在工作"></a>① ByteBuf 如何在工作</h3><p><strong><code>ByteBuf</code> 维护了两个不同的索引：一个是用于读取的 <code>readerIndex </code>， 一个是用于写入的 <code>writerIndex</code>。</strong></p>
<p>写入数据到 <code>ByteBuf</code> 后，<code>writerIndex</code>（写入索引）增加。开始读字节后，<code>readerIndex</code>（读取索引）增加。你可以读取字节，<strong>直到写入索引和读取索引处在相同的位置，<code>ByteBuf </code> 变为不可读</strong>。当访问数据超过数组的最后位，则会抛出 <code>IndexOutOfBoundsException</code>。</p>
<p>调用 <code>ByteBuf </code>的 “<code>read</code>“ 或 “<code>write</code>“ 开头的任何方法都会提升相应的索引。另一方面，”<code>set</code>“ 、 “<code>get</code>“操作字节将不会移动索引位置，他们只会操作相关的通过参数传入方法的相对索引。</p>
<p>可以给 <code>ByteBuf</code> 指定一个最大容量值，这个值限制着 <code>ByteBuf</code> 的容量。任何尝试将写入索引超过这个值的行为都将导致抛出异常。<code>ByteBuf</code> 的默认最大容量限制是 <code>Integer.MAX_VALUE</code>。</p>
<p><code>ByteBuf </code>类似于一个字节数组，最大的区别是读和写的索引可以用来控制对缓冲区数据的访问。下图显示了一个容量为16的空的 <code>ByteBuf </code> 的布局和状态，<code>writerIndex </code> 和 <code>readerIndex </code> 都在索引位置 0 ：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115510192.png" alt="image-20220327115510192" style="zoom:80%;" />

<h3 id="②-ByteBuf-使用模式"><a href="#②-ByteBuf-使用模式" class="headerlink" title="② ByteBuf 使用模式"></a>② ByteBuf 使用模式</h3><p><code>ByteBuf</code> 有多种使用模式，我们可以根据需求构建不同使用模式的 <code>ByteBuf</code>。</p>
<h4 id="Ⅰ-HEAP-BUFFER-堆缓冲区"><a href="#Ⅰ-HEAP-BUFFER-堆缓冲区" class="headerlink" title="Ⅰ HEAP BUFFER (堆缓冲区)"></a>Ⅰ HEAP BUFFER (堆缓冲区)</h4><p><strong>最常用的模式是 <code>ByteBuf</code> 将数据存储在 JVM 的堆空间，实际上是通过数组存储数据， 所以这种模式被称为支撑数组（Backing Array ）</strong>。堆缓冲区可以在没有使用池化的情况下快速分配和释放，非常适合用来处理遗留数据的。它还提供了直接访问数组的方法，通过 <code>ByteBuf.array()</code> 来获取 <code>byte[]</code> 数据。 </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115516455.png" alt="image-20220327115516455" style="zoom:80%;" />

<h4 id="Ⅱ-DIRECT-BUFFER-直接缓冲区"><a href="#Ⅱ-DIRECT-BUFFER-直接缓冲区" class="headerlink" title="Ⅱ DIRECT BUFFER (直接缓冲区)"></a>Ⅱ DIRECT BUFFER (直接缓冲区)</h4><p>在 Java 中，我们创建的对象大部分都是存储在堆区之中的，但这不是绝对的。</p>
<p>在 NIO 的 API 中， <strong>允许 Buffer 分配直接内存，即操作系统的内存</strong>。</p>
<p>这样做的<strong>好处</strong>非常明显： 前面在传输章节介绍过的零拷贝技术的 特点之一就是规避了多次 IO 拷贝。现在数据直接就在直接内存中，而不是在JVM应用进程中，这不仅减少了拷贝次数， 还减少了用户态与内核态的上下文切换。 </p>
<p>直接缓冲区的<strong>缺点</strong>也比较明显： <u>直接内存的分配和释放都较为昂贵，而且因为直接缓冲区的数据不是在堆区的，所以我们在某些时候可能需要将直接缓冲区的数据先拷贝一个副本到堆区， 再对这个副本进行操作</u>。 与支撑数组相比，直接缓冲区的工作可能更多，所以<strong>如果事先知道数据会作为一个数组来被访问，那么我们应该使用堆内存</strong>。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115524895.png" alt="image-20220327115524895" style="zoom:80%;" />

<h4 id="Ⅲ-COMPOSITE-BUFFER-复合缓冲区"><a href="#Ⅲ-COMPOSITE-BUFFER-复合缓冲区" class="headerlink" title="Ⅲ COMPOSITE BUFFER (复合缓冲区)"></a>Ⅲ COMPOSITE BUFFER (复合缓冲区)</h4><p>最后一种模式是复合缓冲区，我们可以创建多个不同的 <code>ByteBuf</code>，然后提供一个这些 <code>ByteBuf</code> 组合的视图 <code>CompositeByteBuf</code>。我们可以动态的向 <code>CompositeByteBuf</code> 中添加和删除其中的 <code>ByteBuf</code> 实例，JDK 的 <code>ByteBuffer</code> 没有这样的功能。</p>
<p>⚠ 警告：<code>CompositeByteBuf.hasArray()</code> 总是返回 false，因为它可能既包含堆缓冲区，也包含直接缓冲区</p>
<p>例如，一条消息由 header 和 body 两部分组成，将 header 和 body 组装成一条消息发送出去，可能 body 相同，只是 header 不同，使用 <code>CompositeByteBuf</code> 就不用每次都重新分配一个新的缓冲区。下图显示<code>CompositeByteBuf </code>组成 header 和 body：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115531192.png" alt="image-20220327115531192" style="zoom:80%;" />

<p>下面代码显示了使用 <strong>JDK 的 <code>ByteBuffer</code> 的一个实现</strong>。两个 <code>ByteBuffer </code>的数组创建保存消息的组件，第三个创建用于保存所有数据的副本。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 使用数组保存消息的各个部分</span>
<span class="token class-name">ByteBuffer</span><span class="token punctuation">[</span><span class="token punctuation">]</span> message <span class="token operator">=</span> <span class="token punctuation">&#123;</span> header<span class="token punctuation">,</span> body <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

<span class="token comment">// 使用副本来合并这两个部分</span>
<span class="token class-name">ByteBuffer</span> message2 <span class="token operator">=</span> <span class="token class-name">ByteBuffer</span><span class="token punctuation">.</span><span class="token function">allocate</span><span class="token punctuation">(</span>
        header<span class="token punctuation">.</span><span class="token function">remaining</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> body<span class="token punctuation">.</span><span class="token function">remaining</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
message2<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>header<span class="token punctuation">)</span><span class="token punctuation">;</span>
message2<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>body<span class="token punctuation">)</span><span class="token punctuation">;</span>
message2<span class="token punctuation">.</span><span class="token function">flip</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这种做法显然是低效的，分配和复制操作不是最优的方法，操纵数组使代码显得很笨拙。</p>
<p>下面看使用 <code>CompositeByteBuf</code> 的改进版本：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ByteBuf</span> headerBuf <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span> <span class="token comment">// 可以是堆缓冲区或直接缓冲区</span>
<span class="token class-name">ByteBuf</span> bodyBuf <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span> <span class="token comment">// 可以是堆缓冲区或直接缓冲区</span>
<span class="token comment">// 追加 ByteBuf 实例的 CompositeByteBuf</span>
<span class="token class-name">CompositeByteBuf</span> messageBuf <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span>
messageBuf<span class="token punctuation">.</span><span class="token function">addComponents</span><span class="token punctuation">(</span>headerBuf<span class="token punctuation">,</span> bodyBuf<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// ....</span>
messageBuf<span class="token punctuation">.</span><span class="token function">removeComponent</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 移除头</span>

<span class="token comment">// 遍历所有 ByteBuf 实例</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> messageBuf<span class="token punctuation">.</span><span class="token function">numComponents</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>                        <span class="token comment">//3</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>messageBuf<span class="token punctuation">.</span><span class="token function">component</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="3-字节级别的操作"><a href="#3-字节级别的操作" class="headerlink" title="3. 字节级别的操作"></a>3. 字节级别的操作</h2><p>除了基本的读写操作， <code>ByteBuf</code> 还提供了它所包含的数据的修改方法。</p>
<h3 id="①-随机访问索引"><a href="#①-随机访问索引" class="headerlink" title="① 随机访问索引"></a>① 随机访问索引</h3><p><code>ByteBuf </code>使用从 0 开始的索引，第一个字节的索引是 0，最后一个字节的索引是 <code>ByteBuf </code>的 capacity - 1，下面代码是遍历 <code>ByteBuf</code> 的所有字节：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ByteBuf</span> buffer <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> buffer<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">byte</span> b <span class="token operator">=</span> buffer<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">char</span><span class="token punctuation">)</span> b<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>⚠ 注意：通过索引访问时不会自动推进 <code>readerIndex</code> （读索引）和 <code>writerIndex</code>（写索引），当然我们可以通过 <code>ByteBuf </code> 的 <code>readerIndex(index)</code> 或 <code>writerIndex(index) </code>来分别推进读索引或写索引</p>
<p>JDK 的 <code>ByteBuffer</code> 只有一个索引 position，所以当 <code>ByteBuffer</code> 在读和写模式之间切换时，需要使用 <code>flip</code> 方法。 而 <code>ByteBuf</code> 同时具有读索引和写索引，则无需切换模式，在 <code>ByteBuf</code> 内部，其索引满足：</p>
<pre class="line-numbers language-text" data-language="text"><code class="language-text">0 &lt;= readerIndex &lt;= writerIndex &lt;= capacity<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>当使用<code>readerIndex</code>读取字节，或使用<code>writerIndex</code>写入字节时，<code>ByteBuf </code>内部的分段大致如下：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115538062.png" alt="image-20220327115538062" style="zoom:80%;" />

<h3 id="②-ByteBuf-内部分段"><a href="#②-ByteBuf-内部分段" class="headerlink" title="② ByteBuf 内部分段"></a>② ByteBuf 内部分段</h3><p>上图介绍了在<code>ByteBuf</code>内部大致有3个分段，接下来我们就详细的介绍下这三个分段。</p>
<h4 id="Ⅰ-可丢弃字节-Discardable-Bytes"><a href="#Ⅰ-可丢弃字节-Discardable-Bytes" class="headerlink" title="Ⅰ 可丢弃字节 Discardable Bytes"></a>Ⅰ 可丢弃字节 Discardable Bytes</h4><p>当<code>readerIndex</code>读取一部分字节后，之前读过的字节就属于已读字节，可以被丢弃了，通过调用 <code>ByteBuf</code>的<code>discardReadBytes</code>方法我们可以丢弃这个分段，<strong>丢弃这个分段实际上是删除这个分段的已读字节， 然后回收这部分空间加入可写入字节</strong>：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115548658.png" alt="image-20220327115548658" style="zoom:80%;" />

<h4 id="Ⅱ-可读取字节-Readable-Bytes"><a href="#Ⅱ-可读取字节-Readable-Bytes" class="headerlink" title="Ⅱ 可读取字节 Readable Bytes"></a>Ⅱ 可读取字节 Readable Bytes</h4><p><code>ByteBuf</code>的可读字节分段存储了尚未读取的字节，我们可以使用<code>readBytes</code>等方法来读取这部分数据，如果我们读取的范围超过了可读字节分段，那么<code>ByteBuf</code>会抛出<code>IndexOutOfBoundsException</code>异常，所以<strong>在读取数据之前，我们 需要使用<code>isReadable</code>方法判断是否仍然有可读字节分段</strong>。</p>
<h4 id="Ⅲ-可写入字节-Writable-Bytes"><a href="#Ⅲ-可写入字节-Writable-Bytes" class="headerlink" title="Ⅲ 可写入字节 Writable Bytes"></a>Ⅲ 可写入字节 Writable Bytes</h4><p>可写字节分段即没有被写入数据的区域，我们可以使用<code>writeBytes</code>等方法向可写字节分段写入数据，如果我们写入 的字节超过了<code>ByteBuf</code>的容量，那么<code>ByteBuf</code>也会抛出<code>IndexOutOfBoundsException</code>异常。</p>
<h3 id="③-索引管理"><a href="#③-索引管理" class="headerlink" title="③ 索引管理"></a>③ 索引管理</h3><p>我们可以通过<code>markReaderIndex</code>，<code>markWriterIndex</code>方法来标记当前<code>readerIndex</code>和<code>writerIndex</code>的位置， 然后使用<code>resetReaderIndex</code>，<code>resetWriterIndex</code>方法来将<code>readerIndex</code>和<code>writerIndex</code>重置为之前标记过的 位置。</p>
<p><u>我们还可以使用<code>clear</code>方法来将<code>readerIndex</code>和<code>writerIndex</code>重置为0，但是<code>clear</code>方法并不会清空<code>ByteBuf</code>的内容</u>，下面<code>clear</code>方法的实现：</p>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/20201211215131.png" style="zoom:80%;" />

<p>其过程是这样的：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115555040.png" alt="image-20220327115555040" style="zoom:80%;" />

<p>由于调用clear后，数据并没有被清空，但整个<code>ByteBuf</code>仍然是可写的，这比<code>discardReadBytes</code>轻量的多， <code>DiscardReadBytes</code>还要回收已读字节空间。</p>
<h3 id="④-查找操作"><a href="#④-查找操作" class="headerlink" title="④ 查找操作"></a>④ 查找操作</h3><p>在<code>ByteBuf</code>中，有多种可以确定值的索引的方法，最简单的方法是使用<code>ByteBuf</code>的<code>indexOf</code>方法。 </p>
<p>较为复杂的查找可以通过<code>ByteBuf</code>的<code>forEachByte</code>方法，<code>forEachByte</code>方法所需的参数是<code>ByteProcessor</code>， 但我们无需去实现<code>ByteProcessor</code>，因为<code>ByteProcessor</code>已经为我们定义好了两个易用的实现。</p>
<p>下面例子展示了寻找一个回车符，<code>\ r</code>的一个例子：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ByteBuf</span> buffer <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> index <span class="token operator">=</span> buffer<span class="token punctuation">.</span><span class="token function">forEachByte</span><span class="token punctuation">(</span><span class="token class-name">ByteBufProcessor</span><span class="token punctuation">.</span>FIND_CR<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h3 id="⑤-衍生缓冲区"><a href="#⑤-衍生缓冲区" class="headerlink" title="⑤ 衍生缓冲区"></a>⑤ 衍生缓冲区</h3><p>衍生缓冲区是专门展示<code>ByteBuf</code>内部数据的视图，这种视图是由 <code>duplicate()</code>, <code>slice()</code>, <code>slice(int, int)</code>,<code>readOnly()</code>, 和 <code>order(ByteOrder)</code> 方法创建的</p>
<p>🚨 这些方法都将以源<code>ByteBuf</code>创建一个新的<code>ByteBuf</code>视图，所以源<code>ByteBuf</code>内部的索引和数据都与视图一样， 但这也意味着修改了视图的内容，也会修改源<code>ByteBuf</code>的内容。即<strong>源 <code>ByteBuf</code> 和视图数据共享</strong>。举个例子，若需要操作某段数据，使用 <code>slice(int, int)</code>：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Charset</span> utf8 <span class="token operator">=</span> <span class="token class-name">Charset</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 创建一个 ByteBuf 保存特定字节串</span>
<span class="token class-name">ByteBuf</span> buf <span class="token operator">=</span> <span class="token class-name">Unpooled</span><span class="token punctuation">.</span><span class="token function">copiedBuffer</span><span class="token punctuation">(</span><span class="token string">"Netty in Action rocks!"</span><span class="token punctuation">,</span> utf8<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//1</span>

<span class="token comment">// 创建从索引 0 开始，并在 14 结束的新 ByteBuf 视图</span>
<span class="token class-name">ByteBuf</span> sliced <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sliced<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>utf8<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 更新源 Bytebuf 索引 0 的字节</span>
buf<span class="token punctuation">.</span><span class="token function">setByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">)</span> <span class="token string">'J'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// true：源 Bytebuf 更新，视图也会更新</span>
<span class="token keyword">assert</span> buf<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">==</span> sliced<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果我们需要一个真实的<code>ByteBuf</code>的副本， 我们应该使用<code>copy</code>方法来创建，<code>copy</code>方法创建的副本拥有独立的内存，不会影响到源<code>ByteBuf</code>：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Charset</span> utf8 <span class="token operator">=</span> <span class="token class-name">Charset</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 创建一个 ByteBuf 保存特定字节串</span>
<span class="token class-name">ByteBuf</span> buf <span class="token operator">=</span> <span class="token class-name">Unpooled</span><span class="token punctuation">.</span><span class="token function">copiedBuffer</span><span class="token punctuation">(</span><span class="token string">"Netty in Action rocks!"</span><span class="token punctuation">,</span> utf8<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">//1</span>

<span class="token comment">// 创建从索引 0 开始，并在 14 结束的新 ByteBuf 拷贝</span>
<span class="token class-name">ByteBuf</span> copy <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">copy</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>copy<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>utf8<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 更新源 Bytebuf 索引 0 的字节</span>
buf<span class="token punctuation">.</span><span class="token function">setByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">)</span> <span class="token string">'J'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// false：源 Bytebuf 和拷贝副本互不影响</span>
<span class="token keyword">assert</span> buf<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">!=</span> copy<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑥-读-写操作"><a href="#⑥-读-写操作" class="headerlink" title="⑥ 读/写操作"></a>⑥ 读/写操作</h3><p>读/写操作主要由2类：</p>
<ul>
<li><code>get()/set()</code> 操作从给定的索引开始，保持不变</li>
<li><code>read()/write()</code> 操作从给定的索引开始，与字节访问的数量来适用，递增当前的写索引或读索引</li>
</ul>
<h4 id="Ⅰ-get-set"><a href="#Ⅰ-get-set" class="headerlink" title="Ⅰ get/set"></a>Ⅰ get/set</h4><p><code>ByteBuf </code>的各种读写方法或其他一些检查方法可以看 ByteBuf 的 API，下面是常见的 <code>get()</code> 操作：</p>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>getBoolean(int)</code></td>
<td>返回当前索引的 Boolean 值</td>
</tr>
<tr>
<td><code>getByte(int)</code> , <code>getUnsignedByte(int)</code></td>
<td>返回当前索引的(无符号)字节</td>
</tr>
<tr>
<td><code>getMedium(int)</code> , <code>getUnsignedMedium(int)</code></td>
<td>返回当前索引的 (无符号) 24-bit 中间值</td>
</tr>
<tr>
<td><code>getInt(int)</code> , <code>getUnsignedInt(int)</code></td>
<td>返回当前索引的(无符号) 整型</td>
</tr>
<tr>
<td><code>getLong(int)</code>, <code>getUnsignedLong(int)</code></td>
<td>返回当前索引的 (无符号) Long 型</td>
</tr>
<tr>
<td><code>getShort(int)</code> , <code>getUnsignedShort(int)</code></td>
<td>返回当前索引的 (无符号) Short 型</td>
</tr>
<tr>
<td><code>getBytes(int, ...)</code></td>
<td>字节</td>
</tr>
</tbody></table>
<p>常见 <code>set()</code> 操作如下：</p>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>setBoolean(int, boolean)</code></td>
<td>在指定的索引位置设置 Boolean 值</td>
</tr>
<tr>
<td><code>setByte(int, int)</code></td>
<td>在指定的索引位置设置 byte 值</td>
</tr>
<tr>
<td><code>setMedium(int, int)</code></td>
<td>在指定的索引位置设置 24-bit 中间 值</td>
</tr>
<tr>
<td><code>setInt(int, int)</code></td>
<td>在指定的索引位置设置 int 值</td>
</tr>
<tr>
<td><code>setLong(int, long)</code></td>
<td>在指定的索引位置设置 long 值</td>
</tr>
<tr>
<td><code>setShort(int, int)</code></td>
<td>在指定的索引位置设置 short 值</td>
</tr>
</tbody></table>
<p>下面是用法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Charset</span> utf8 <span class="token operator">=</span> <span class="token class-name">Charset</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 创建一个新的 ByteBuf 给指定 String 保存字节</span>
<span class="token class-name">ByteBuf</span> buf <span class="token operator">=</span> <span class="token class-name">Unpooled</span><span class="token punctuation">.</span><span class="token function">copiedBuffer</span><span class="token punctuation">(</span><span class="token string">"Netty in Action rocks!"</span><span class="token punctuation">,</span> utf8<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 打印的第一个字符，`N`</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">char</span><span class="token punctuation">)</span>buf<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 存储当前 readerIndex 和 writerIndex</span>
<span class="token keyword">int</span> readerIndex <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">readerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token keyword">int</span> writerIndex <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">writerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 更新索引 0 的字符 `B`</span>
buf<span class="token punctuation">.</span><span class="token function">setByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">)</span><span class="token string">'B'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 打印出的第一个字符，现在是 `B`</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">char</span><span class="token punctuation">)</span>buf<span class="token punctuation">.</span><span class="token function">getByte</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 断言成功，因为setByte 和 getByte 永远不会改变索引</span>
<span class="token keyword">assert</span> readerIndex <span class="token operator">==</span> buf<span class="token punctuation">.</span><span class="token function">readerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">assert</span> writerIndex <span class="token operator">==</span>  buf<span class="token punctuation">.</span><span class="token function">writerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="Ⅱ-read-write"><a href="#Ⅱ-read-write" class="headerlink" title="Ⅱ read/write"></a>Ⅱ read/write</h4><p>现在，让我们来看看 <code>read()</code> 操作，对当前 <code>readerIndex </code>或 <code>writerIndex </code>进行操作。这些用于从 <code>ByteBuf </code>读取就好像它是一个流。下面展示了常见的 <code>read()</code> 方法：</p>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>readBoolean()</code></td>
<td>Reads the Boolean value at the current readerIndex and increases the readerIndex by 1.</td>
</tr>
<tr>
<td><code>readByte()　</code>, <code>readUnsignedByte()</code></td>
<td>Reads the (unsigned) byte value at the current readerIndex and increases　the readerIndex by 1.</td>
</tr>
<tr>
<td><code>readMedium()</code>,　<code>readUnsignedMedium()</code></td>
<td>Reads the (unsigned) 24-bit medium value at the current readerIndex and　increases the readerIndex by 3.</td>
</tr>
<tr>
<td><code>readInt()</code>,　<code>readUnsignedInt()</code></td>
<td>Reads the (unsigned) int value at the current readerIndex and increases　the readerIndex by 4.</td>
</tr>
<tr>
<td><code>readLong()</code>,　<code>readUnsignedLong()</code></td>
<td>Reads the (unsigned) int value at the current readerIndex and increases　the readerIndex by 8.</td>
</tr>
<tr>
<td><code>readShort()</code>,　<code>readUnsignedShort()</code></td>
<td>Reads the (unsigned) int value at the current readerIndex and increases　the readerIndex by 2.</td>
</tr>
<tr>
<td><code>readBytes(int,int, ...)</code></td>
<td>Reads the value on the current readerIndex for the given length into the　given object. Also increases the readerIndex by the length.</td>
</tr>
</tbody></table>
<p>每个 <code>read()</code> 方法都对应一个<code>write()</code>。下面展示了常见的 <code>write()</code> 方法：</p>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>writeBoolean(boolean)</code></td>
<td>Writes the Boolean value on the current writerIndex and increases the　writerIndex by 1.</td>
</tr>
<tr>
<td><code>writeByte(int)</code></td>
<td>Writes the byte value on the current writerIndex and increases the　writerIndex by 1.</td>
</tr>
<tr>
<td><code>writeMedium(int)</code></td>
<td>Writes the medium value on the current writerIndex and increases the　writerIndex by 3.</td>
</tr>
<tr>
<td><code>writeInt(int)</code></td>
<td>Writes the int value on the current writerIndex and increases the　writerIndex by 4.</td>
</tr>
<tr>
<td><code>writeLong(long)</code></td>
<td>Writes the long value on the current writerIndex and increases the　writerIndex by 8.</td>
</tr>
<tr>
<td><code>writeShort(int)</code></td>
<td>Writes the short value on the current writerIndex and increases thewriterIndex by 2.</td>
</tr>
<tr>
<td><code>writeBytes(int，...）</code></td>
<td>Transfers the bytes on the current writerIndex from given resources.</td>
</tr>
</tbody></table>
<p>下面是用法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Charset</span> utf8 <span class="token operator">=</span> <span class="token class-name">Charset</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 创建一个新的 ByteBuf 保存给定 String 的字节。</span>
<span class="token class-name">ByteBuf</span> buf <span class="token operator">=</span> <span class="token class-name">Unpooled</span><span class="token punctuation">.</span><span class="token function">copiedBuffer</span><span class="token punctuation">(</span><span class="token string">"Netty in Action rocks!"</span><span class="token punctuation">,</span> utf8<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 打印的第一个字符，`N`</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">char</span><span class="token punctuation">)</span>buf<span class="token punctuation">.</span><span class="token function">readByte</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 存储当前的 readerIndex 和 writerIndex</span>
<span class="token keyword">int</span> readerIndex <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">readerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> writerIndex <span class="token operator">=</span> buf<span class="token punctuation">.</span><span class="token function">writerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 更新索引 0 的字符 `B`</span>
buf<span class="token punctuation">.</span><span class="token function">writeByte</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">)</span><span class="token string">'?'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 断言成功，因为 writeByte() 移动了 writerIndex</span>
<span class="token keyword">assert</span> readerIndex <span class="token operator">==</span> buf<span class="token punctuation">.</span><span class="token function">readerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">assert</span> writerIndex <span class="token operator">!=</span> buf<span class="token punctuation">.</span><span class="token function">writerIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="4-ByteBufHolder"><a href="#4-ByteBufHolder" class="headerlink" title="4. ByteBufHolder"></a>4. ByteBufHolder</h2><p>从表面理解起来，**<code>ByteBufHolder</code>是<code>ByteBuf</code>的持有者**，的确没有错。 </p>
<p><strong><code>ByteBuf</code>几乎唯一的作用就是存储数据，但在实际的数据传输中，除了数据，我们可能还需要存储各种属性值</strong>，Http便是一个很好的例子。 除了Http Content，还包括状态码，cookie等等属性，总不能把这些属性与Content存储在一个ByteBuf中吧， 所以Netty提供了<code>ByteBufHolder</code>。<code>ByteBufHolder</code>为Netty提供了高级特性的支持，如缓冲区持化，使得可以从池中借用<code>ByteBuf</code>，并且在需要的时候自动释放。</p>
<p>以下是<code>ByteBufHolder</code>常见的方法：</p>
<ul>
<li><code>content</code>: 返回这个<code>ByteBufHolder</code>所持有的<code>ByteBuf</code>。</li>
<li><code>copy</code>： 返回<code>ByteBufHolder</code>的深拷贝，连它持有的<code>ByteBuf</code>也拷贝。</li>
</ul>
<h2 id="5-ByteBuf-分配"><a href="#5-ByteBuf-分配" class="headerlink" title="5. ByteBuf 分配"></a>5. ByteBuf 分配</h2><p>前面介绍了ByteBuf的一些基本操作和原理，但却并未说明如何分配一个<code>ByteBuf</code>，这里将讲解<code>ByteBuf</code>的分配方式。</p>
<h3 id="①-ByteBufAllocator"><a href="#①-ByteBufAllocator" class="headerlink" title="① ByteBufAllocator"></a>① ByteBufAllocator</h3><p>为了减少分配和释放内存的开销，Netty通过 <code>ByteBufAllocator </code>实现了<code>ByteBuf</code>的<strong>池化</strong>。以下是<code>ByteBufAllocator </code>的常见方法。</p>
<ul>
<li><code>buffer</code>: 返回一个基于堆或直接内存的ByteBuf，具体取决于实现。</li>
<li><code>heapBuffer</code>： 返回一个基于堆内存的ByteBuf。</li>
<li><code>directBuffer</code>： 返回一个基于直接内存的ByteBuf。</li>
<li><code>compositeBuffer</code>： 返回一个组合ByteBuf。</li>
<li><code>ioBuffer</code>： 返回一个用于套接字的ByteBuf。</li>
</ul>
<p>我们可以通过<code>Channel</code>或<code>ChannelHandlerContext</code>的<code>alloc</code>方法获取到一个<code>ByteBufAllocator</code></p>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/20201211222412.png" style="zoom:80%;" />

<p>Netty提供了两种<code>ByteBufAllocator</code>的实现： <code>PooledByteBufAllocator</code>和<code>UnpooledByteBufAllocator</code>。 <code>PooledByteBufAllocator</code>池化了<code>ByteBuf</code>的实例以提高性能并最大限度的减少内存碎片，此实现的分配内存的方法 是使用 <a target="_blank" rel="noopener" href="https://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf">jemalloc</a>，此种 方法分配内存的效率非常高，已被大量现代操作系统采用。 <code>UnpooledByteBufAllocator</code>则不会池化<code>ByteBuf</code>， Netty默认使用的是<code>PooledByteBufALlocator</code>。</p>
<h3 id="②-Unpooled-非池化"><a href="#②-Unpooled-非池化" class="headerlink" title="② Unpooled 非池化"></a>② Unpooled 非池化</h3><p>当<code>Channel</code>或<code>ChannelHandlerContext</code>未引用<code>ByteBufAllocator</code>时，就无法使用<code>ByteBufAllocator</code>来分配 <code>ByteBUf</code>，对于这种情况，Netty提供了<code>Unpooled</code>工具类，它提供了一系列的<strong>静态方法</strong>来分配<strong>未池化</strong>的<code>ByteBuf</code>。</p>
<h3 id="③-ByteBufUtil"><a href="#③-ByteBufUtil" class="headerlink" title="③ ByteBufUtil"></a>③ ByteBufUtil</h3><p><code>ByteBufUtil</code>是<code>ByteBuf</code>的一个工具类，它提供大量操作<code>ByteBuf</code>的方法，，其中非常重要的一个方法就是 <code>hexDump</code>，这个方法会以16进制的形式来表示<code>ByteBuf</code>的内容。另一个很重要的方法是<code>equals</code>，它被用于判断 <code>ByteBuf</code>之间的相等性。</p>
<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><blockquote>
<p>《Netty 实战》</p>
</blockquote>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Gtwff</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2022/01/02/Netty/ByteBuf-%E8%AF%A6%E8%A7%A3/">https://kuangty.gitee.io/2022/01/02/Netty/ByteBuf-%E8%AF%A6%E8%A7%A3/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Gtwff</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/ByteBuf-%E8%AF%A6%E8%A7%A3/">
                                    <span class="chip bg-color">ByteBuf 详解</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/01/02/Netty/ChannelHandler-%E4%B8%8E-ChannelPipeline-%E8%AF%A6%E8%A7%A3/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/13.jpg" class="responsive-img" alt="ChannelHandler 与 ChannelPipeline 详解">
                        
                        <span class="card-title">ChannelHandler 与 ChannelPipeline 详解</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-01-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Netty/" class="post-category">
                                    Netty
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/ChannelHandler-%E4%B8%8E-ChannelPipeline-%E8%AF%A6%E8%A7%A3/">
                        <span class="chip bg-color">ChannelHandler 与 ChannelPipeline 详解</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/01/02/Netty/Transport-%E8%AF%A6%E8%A7%A3/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/12.jpg" class="responsive-img" alt="Transport 详解">
                        
                        <span class="card-title">Transport 详解</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-01-02
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Netty/" class="post-category">
                                    Netty
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Transport-%E8%AF%A6%E8%A7%A3/">
                        <span class="chip bg-color">Transport 详解</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
